package com.share.dgs.fetcher;

import com.netflix.graphql.dgs.*;
import com.netflix.graphql.dgs.context.DgsContext;
import com.share.dgs.context.MyContext;
import com.share.dgs.exception.MyException;
import graphql.GraphQLException;
import graphql.schema.DataFetchingEnvironment;
import org.dataloader.DataLoader;
import org.springframework.util.StringUtils;

import java.util.concurrent.CompletableFuture;

/**
 * @author caifan
 * @created 2021/3/5
 * description:
 */
@DgsComponent
public class HelloDataFetcher {

    @DgsData(parentType = "Query", field = "hello")
    @DgsEnableDataFetcherInstrumentation(value = true)
    public String hello(@InputArgument("name") String name, DgsDataFetchingEnvironment environment) throws Exception {
        if (StringUtils.isEmpty(name)) {
            name = "Stranger";
        }
        return "hello:" + name + "!";
    }

    @DgsData(parentType = "Query", field = "messageFromBatchLoader")
    public CompletableFuture<String> getMessage(DataFetchingEnvironment env) {
        DataLoader<String, String> dataLoader = env.getDataLoader("messages");
        return dataLoader.load("a");
    }

    @DgsData(parentType = "Query", field = "withContext")
    public String withContext(DataFetchingEnvironment dfe) {
        MyContext customContext = DgsContext.getCustomContext(dfe);
        return customContext.getCustomState();
    }

    @DgsData(parentType = "Query", field = "withDataLoaderContext")
    @DgsEnableDataFetcherInstrumentation
    public CompletableFuture<String> withDataLoaderContext(DataFetchingEnvironment dfe) {
        DataLoader<String, String> exampleLoaderWithContext = dfe.getDataLoader("exampleLoaderWithContext");
        return exampleLoaderWithContext.load("A");
    }

    @DgsData(parentType = "Query", field = "withGraphqlException")
    public String withGraphqlException() {
        throw new GraphQLException("that's not going to work!");
    }

    @DgsData(parentType = "Query", field = "withRuntimeException")
    public String withRuntimeException() {
        throw new RuntimeException("That's broken!");
    }

    @DgsQuery(field = "myError")
    public String myException() {
        throw new MyException("1000", "错误啦");
    }
}
